package cn.changeforyou.analyzer.combine.orm;

import cn.changeforyou.analyzer.javaparse.model.EntityModel;
import cn.changeforyou.analyzer.javaparse.model.EntityModel.FieldInfo;
import cn.changeforyou.analyzer.naming.NamingStrategy;
import java.util.ArrayList;
import java.util.List;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Setter
public class TableWriter {
	
	private NamingStrategy namingStrategy;
	private String idStruct;
	
	public String printCreateTableSql(EntityModel entityModel) {
		List<String> primaryKeys = new ArrayList<>();
		StringBuilder sb = new StringBuilder("CREATE TABLE IF NOT EXISTS `").append(entityModel.getTableName()).append("`(\n");
		for (FieldInfo fieldInfo : entityModel.getFieldInfos()) {
			String name = fieldInfo.getName();
			String struct = fieldInfo.getJavaType();
			String type = "";
			switch (struct) {
				case "String":
					if (name.endsWith("Id")) {
						type = "VARCHAR(32)";
					} else {
						type = "VARCHAR(255)";
					}
					break;
				case "BigDecimal":
					type = "DECIMAL(6,2) DEFAULT 0";
					break;
				case "Integer":
					type = "INT";
					break;
				case "Double":
					type = "DOUBLE(8,2)";
					break;
				case "LocalDateTime":
					type = "DATETIME";
					break;
				case "Long":
					type = "BIGINT";
					break;
				default:
					log.error("发现了额外的数据结构, 直接当做varchar {}", struct);
					type = "VARCHAR(255)";
			}
			if (fieldInfo.isPrimaryKey()) {
				primaryKeys.add(fieldInfo.getName());
				sb.append(namingStrategy.getName(name, null)).append(" ").append(type).append(" NOT NULL ").append("COMMENT '").append(fieldInfo.getComment()).append("',\n");
			}else {
				sb.append(namingStrategy.getName(name, null)).append(" ").append(type).append(" NULL ").append("COMMENT '").append(fieldInfo.getComment()).append("',\n");
			}
		}
		sb.append(" PRIMARY KEY (");
		if (primaryKeys.size() == 1) {
			sb.append(primaryKeys.get(0));
		} else {
			for (String primaryKey : primaryKeys) {
				sb.append(primaryKey).append(", ");
			}
			sb.delete(sb.length() - 2, sb.length());
		}
		sb.append(")\n)  ENGINE=INNODB DEFAULT CHARSET=utf8 COMMENT='").append(entityModel.getTableComment()).append("'");
		return sb.toString();
	}
}
